/*
 * Powered By XY
 * Since 2020
 */

package com.xy.biz.uc.service.impl;

import com.xy.biz.uc.client.UserClient;
import com.xy.biz.uc.domain.bo.*;
import com.xy.biz.uc.domain.converter.UserConverter;
import com.xy.biz.uc.domain.query.*;
import com.xy.biz.uc.domain.req.*;
import com.xy.biz.uc.domain.resp.ListUserGroupItemResponse;
import com.xy.biz.uc.domain.vo.GroupRoleUserTree;
import com.xy.biz.uc.domain.vo.GroupUserTreeItem;
import com.xy.biz.uc.manager.ResourceManager;
import com.xy.biz.uc.manager.RoleManager;
import com.xy.biz.uc.manager.TeamManager;
import com.xy.biz.uc.manager.UserManager;
import com.xy.biz.uc.service.RoleService;
import com.xy.biz.uc.service.UserGroupService;
import com.xy.biz.uc.service.UserService;
import com.xy.lang.domain.Result;
import com.xy.lang.domain.treeing.Tree;
import com.xy.lang.domain.treeing.TreeItem;
import com.xy.tool.concurrent.locks.DisLock;
import com.xy.tool.concurrent.locks.DisLockFactory;
import com.xy.tool.context.UserContextHolder;
import com.xy.tool.minio.domain.resp.AvatarInfoResponse;
import com.xy.tool.minio.util.MinioUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.util.ObjectUtils;
import org.springframework.util.StringUtils;

import java.time.LocalDateTime;
import java.util.*;
import java.util.stream.Collectors;

import static com.xy.biz.uc.domain.bo.TeamUserRelBO.JOIN_STATUS_JOINED;
import static com.xy.biz.uc.domain.constant.RoleConstant.*;

/**
 *
 *
 * @author zsp
 * @date 2020-8-19
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserManager userManager;
    @Autowired
    private RoleManager roleManager;
    @Autowired
    private ResourceManager resourceManager;
    @Autowired
    private DisLockFactory disLockFactory;
    @Autowired
    private MinioUtil minioUtil;
    @Autowired
    private UserGroupService userGroupService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private TeamManager teamManager;
    @Autowired
    private UserClient userClient;

    @Value("${user.head-portrait-path}")
    private String headPortraitPath;

    @Override
    public Result<?> saveUserByUserCode(UserBO userBO) {
        String userCode = userBO.getUserCode();
        String lockKey = "1user-" + userCode;
        DisLock disLock = disLockFactory.create();
        if (disLock.lock(lockKey, 5000L)) {
            try {
                if (userManager.isUserCodeExists(userCode)) {
                    return Result.ofConflict("用户名已注册", userCode);
                }
                userBO.setStatus(0);
                userBO.setTenantId(0L);
                Long createUserId = UserContextHolder.getUserId();
                userBO.setCreateUserId(createUserId == null ? 0 : createUserId);
                userBO.setCreateTime(LocalDateTime.now());
                userBO.setUpdateTime(LocalDateTime.now());
                int affectedRows = userManager.saveUser(userBO);
                if (affectedRows > 0) {
                    return Result.success();
                }
            } finally {
                disLock.unlock(lockKey);
            }
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> saveUserByMobile(UserBO userBO) {
        String mobile = userBO.getMobile();
        String lockKey = "2user-" + mobile;
        DisLock disLock = disLockFactory.create();
        if (disLock.lock(lockKey, 5000L)) {
            try {
                if (userManager.isMobileExists(mobile)) {
                    return Result.ofConflict("手机已注册", mobile);
                }
                userBO.setUserCode(mobile);
                userBO.setStatus(0);
                userBO.setTenantId(UserContextHolder.getTenantId());
                userBO.setCreateTime(LocalDateTime.now());
                userBO.setUpdateTime(LocalDateTime.now());
                int affectedRows = userManager.saveUser(userBO);
                if (affectedRows > 0) {
                    return Result.success();
                }
            } finally {
                disLock.unlock(lockKey);
            }
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> saveUserByEmail(UserBO userBO) {
        String email = userBO.getEmail();
        String lockKey = "3user-" + email;
        DisLock disLock = disLockFactory.create();
        if (disLock.lock(lockKey, 5000L)) {
            try {
                if (userManager.isEmailExists(email)) {
                    return Result.ofConflict("邮件已注册", email);
                }
                userBO.setUserCode(email);
                userBO.setStatus(0);
                userBO.setTenantId(UserContextHolder.getTenantId());
                userBO.setCreateTime(LocalDateTime.now());
                userBO.setUpdateTime(LocalDateTime.now());
                int affectedRows = userManager.saveUser(userBO);
                if (affectedRows > 0) {
                    return Result.success();
                }
            } finally {
                disLock.unlock(lockKey);
            }
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> updateUser(UserBO userBO) {
        userBO.setUpdateTime(LocalDateTime.now());
        int affectedRows = userManager.updateUser(userBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    /**
     * 禁闭/解禁用户
     *
     * @param userBO
     */
    @Override
    public Result<?> lockUser(UserBO userBO) {
        int affectedRows = userManager.lockUser(userBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> updateUserBaseInfo(UserBO userBO) {
        userBO.setUpdateTime(LocalDateTime.now());
        if (Objects.isNull(userBO.getUserId())) {
            userBO.setUserId(UserContextHolder.getUserId());
        }
        int affectedRows = userManager.updateUserBaseInfo(userBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Result<?> deleteUser(Long userId) {
        int affectedRows = userManager.deleteUser(userId);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public UserBO getUser(UserIdQuery userIdQuery) {
        UserBO user = userManager.getUser(userIdQuery);
        if (Objects.nonNull(user)) {
            if (StringUtils.hasText(user.getAvatar())) {
                try {
                    String avatar = minioUtil.getObjectURL(headPortraitPath, user.getAvatar(), null);
                    user.setAvatar(avatar);
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
            return user;
        }
        return null;
    }

    /**
     * 是否包含权限
     */
    @Override
    public boolean hasPermission() {
        UserBO user = userManager.getUser(UserIdQuery.builder().withRole(true).withUserGroup(true).build().addUserId(UserContextHolder.getUserId()));
        Set<String> roleBOSet = user.getRoleBOSet().stream().map(RoleBO::getRoleCode).collect(Collectors.toSet());
//        if (roleBOSet.contains(DIRECTOR) && "YX".equals(user.getUserGroupBO().getUserGroupAbbr())) {
        if (roleBOSet.contains(DIRECTOR)) {
            return true;
        }
        //不是营销中心的总监或管理者则加权限
        return roleBOSet.contains(PRESIDENT) || roleBOSet.contains(ADMIN);
    }

    @Override
    public boolean isInRole(String includeRoleCode, Collection<String> excludeRoleCodeCollection, boolean mandatory) {
        if (!CollectionUtils.isEmpty(excludeRoleCodeCollection)) {
            if (excludeRoleCodeCollection.contains(includeRoleCode)) {
                return false;
            }
        }
        Set<String> roleCodeSet = new HashSet<>();
        roleCodeSet.add(includeRoleCode);
        if (!CollectionUtils.isEmpty(excludeRoleCodeCollection)) {
            roleCodeSet.addAll(excludeRoleCodeCollection);
        }
        List<RoleBO> roleBOList = roleManager.listRoleByCode(roleCodeSet);
        if (!CollectionUtils.isEmpty(roleBOList)) {
            Long includeRoleId = null;
            List<Long> excludeRoleIdList = new ArrayList<>();
            for (RoleBO roleBO : roleBOList) {
                if (Objects.equals(includeRoleCode, roleBO.getRoleCode())) {
                    includeRoleId = roleBO.getRoleId();
                } else {
                    excludeRoleIdList.add(roleBO.getRoleId());
                }
            }
            if (includeRoleId != null) {
                List<Long> roleIdList = userManager.listRoleIdByUserId(UserContextHolder.getUserId());
                if (!CollectionUtils.isEmpty(roleIdList)) {
                    if (mandatory && roleIdList.size() == 1 && Objects.equals(roleIdList.get(0), includeRoleId)) {
                        return true;
                    }
                    return roleIdList.indexOf(includeRoleId) > -1
                            && (excludeRoleIdList.size() == 0 || !roleIdList.stream().anyMatch(e -> excludeRoleIdList.contains(e)));
                }
            }
        }
        return false;
    }

    @Override
    public boolean isInRole(Collection<String> includeRoleCodeCollection, Collection<String> excludeRoleCodeCollection, boolean mandatory) {
        if (!CollectionUtils.isEmpty(excludeRoleCodeCollection)) {
            if (excludeRoleCodeCollection.containsAll(includeRoleCodeCollection)) {
                return false;
            }
        }
        Set<String> roleCodeSet = new HashSet<>();
        roleCodeSet.addAll(includeRoleCodeCollection);
        if (!CollectionUtils.isEmpty(excludeRoleCodeCollection)) {
            roleCodeSet.addAll(excludeRoleCodeCollection);
        }
        List<RoleBO> roleBOList = roleManager.listRoleByCode(roleCodeSet);
        if (!CollectionUtils.isEmpty(roleBOList)) {
            List<Long> includeRoleIdList = new ArrayList<>();
            List<Long> excludeRoleIdList = new ArrayList<>();
            for (RoleBO roleBO : roleBOList) {
                if (includeRoleCodeCollection.contains(roleBO.getRoleCode())) {
                    includeRoleIdList.add(roleBO.getRoleId());
                } else {
                    excludeRoleIdList.add(roleBO.getRoleId());
                }
            }
            if (!CollectionUtils.isEmpty(includeRoleIdList)) {
                List<Long> roleIdList = userManager.listRoleIdByUserId(UserContextHolder.getUserId());
                if (!CollectionUtils.isEmpty(roleIdList)) {
                    if (mandatory && roleIdList.size() == includeRoleIdList.size()
                            && roleIdList.containsAll(includeRoleIdList)
                            && (excludeRoleIdList.size() == 0 || !roleIdList.stream().anyMatch(e -> excludeRoleIdList.contains(e)))) {
                        return true;
                    }
                    return includeRoleIdList.stream().anyMatch(e -> roleIdList.contains(e))
                            && (excludeRoleIdList.size() == 0 || !roleIdList.stream().anyMatch(e -> excludeRoleIdList.contains(e)));
                }
            }
        }
        return false;
    }

    /**
     * 根据用户名查找一个
     *
     * @param query
     * @return
     */
    @Override
    public UserBO getUserByUserName(UserQuery query) {
        return userManager.getUserByName(query);
    }

    @Override
    public List<UserBO> getUserByUserNameS(Collection<String> collection) {
        return userManager.getUserByNameS(collection);
    }

    /**
     * 查找多个
     *
     * @param ids 查找条件
     */
    @Override
    public List<UserBO> listUserByUserGroup(Collection<Long> ids) {
        if (CollectionUtils.isEmpty(ids)) {
            return null;
        }
        return userManager.getUsersByGroupIds(ids);
    }

    @Override
    public Result<?> getUserAvatar() {
        AvatarInfoResponse avatarInfoResponse = new AvatarInfoResponse();
        UserBO user = userManager.getUser(UserIdQuery.builder().build().addUserId(UserContextHolder.getUserId()));
        if (user.getAvatar() != null && user.getAvatar().trim() != "") {
            try {
                String objectURL = minioUtil.getObjectURL(headPortraitPath, user.getAvatar(), null);
                avatarInfoResponse.setAvatar(user.getAvatar());
                avatarInfoResponse.setAvatarUrl(objectURL);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return Result.success(avatarInfoResponse);
    }

    @Override
    public UserBO getUserByUserCode(UserCodeQuery userCodeQuery) {
        return userManager.getUserByUserCode(userCodeQuery);
    }

    @Override
    public List<UserBO> listUserById(UserIdQuery userIdQuery) {
        return userManager.listUserById(userIdQuery);
    }

    @Override
    public List<UserBO> listUser(UserQuery query) {
        return userManager.listUser(query);
    }

    @Override
    public int countUser(UserQuery query) {
        return userManager.countUser(query);
    }

    @Override
    public List<UserBO> listUserByRoleId(Collection<Long> collection) {
        return userManager.listUserByRoleId(collection);
    }

    @Override
    public List<Long> listRoleIdByUserId(Long userId) {
        return userManager.listRoleIdByUserId(userId);
    }

    @Transactional
    @Override
    public Result<?> saveOrUpdateUserGroupUser(Long userGroupId, Long userId) {
        if (null == userGroupId) {
            userManager.deleteUserGroupUser(userId);
            return Result.success();
        } else {
            String lockKey = "userg-" + userId;
            DisLock disLock = disLockFactory.create();
            if (disLock.lock(lockKey, 5000L)) {
                try {
                    Long foundUserGroupId = userManager.getUserGroupId(userId);
                    if (null == foundUserGroupId) {
                        userManager.saveUserGroupUser(userGroupId, userId);
                    } else {
                        if (!Objects.equals(foundUserGroupId, userGroupId)) {
                            userManager.deleteUserGroupUser(userId);
                            userManager.saveUserGroupUser(userGroupId, userId);
                        }
                    }
                    return Result.success();
                } finally {
                    disLock.unlock(lockKey);
                }
            }
            return Result.ofErrorRowsAffected();
        }
    }

    @Override
    public Result<?> deleteUserGroupUser(Long userId) {
        userManager.deleteUserGroupUser(userId);
        return Result.success();
    }

    @Override
    public Long getUserGroupId(Long userId) {
        return userManager.getUserGroupId(userId);
    }

    @Override
    public Result<?> setUserAvatar(String avatar) {
        UserBO userBO = new UserBO();
        userBO.setUpdateTime(LocalDateTime.now());
        userBO.setUserId(UserContextHolder.getUserId());
        userBO.setAvatar(avatar);
        int affectedRows = userManager.updateUserBaseInfo(userBO);
        if (affectedRows > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public GroupRoleUserTree listUsers(ListUserRequest request) {
        List<UserBO> userBOS = userManager.listUser(
                UserQuery.max().withRole(true).withUserGroup(true).status(request.getStatus()).build());
        //没有部门的用户不出现在公司树上
        userBOS = userBOS.stream().filter(u -> u.getUserGroupBO() != null).collect(Collectors.toList());
        List<ListUserGroupItemResponse> responses = userGroupService.listUserGroupItem(
                ListUserGroupItemRequest.builder().build());
        //构建公司部门树
        List<TreeItem> treeItems = new ArrayList<>();
        if (!CollectionUtils.isEmpty(responses)) {
            treeItems = Tree.buildTreeItem(responses,
                    e -> e.getSource().getUserGroupId(),
                    e -> e.getSource().getParentUserGroupId(),
                    e -> e == null || e == 0,
                    e -> e.getUserGroupId().toString(),
                    ListUserGroupItemResponse::getUserGroupName,
                    null,
                    null);
        }
        List<GroupUserTreeItem> groupUserTreeItems = new ArrayList<>();
        getGroupItem(treeItems, groupUserTreeItems);
        List<GroupUserTreeItem> userTree = new ArrayList<>();
        //将所有人员先转换成节点
        userBOS.forEach(u -> {
            if (u.getUserGroupBO() != null) {
                GroupUserTreeItem g = new GroupUserTreeItem();
                g.setPerson(true);
                g.setId(u.getUserId());
                g.setLabel(u.getUserName());
                g.setTag(u.getUserGroupBO().getUserGroupId());
                userTree.add(g);
            }
        });
        Map<Object, List<GroupUserTreeItem>> userNode = userTree.stream().collect(Collectors.groupingBy(GroupUserTreeItem::getTag));
        //将人员节点添加进部门
        getUserItem(groupUserTreeItems, userNode);

        ArrayList<Integer> typeList = new ArrayList<>();
        typeList.add(1);
        typeList.add(2);
        List<RoleBO> roleItemList = roleService.listRole(RoleQuery.max().typeList(typeList).build());

        List<GroupUserTreeItem> roleUserTreeItems = new ArrayList<>();
        roleItemList.forEach(
                item -> {
                    GroupUserTreeItem treeItem = new GroupUserTreeItem();
                    treeItem.setId(item.getRoleId());
                    treeItem.setLabel(item.getName());
                    treeItem.setPerson(false);
                    roleUserTreeItems.add(treeItem);
                }
        );
        List<UserBO> finalUserBOS = userBOS;
        roleUserTreeItems.forEach(
                item -> {
                    for (UserBO userBO : finalUserBOS) {

                        if (ObjectUtils.isEmpty(userBO.getRoleBOSet()))
                            continue;
                        if (userBO.getRoleBOSet().stream().map(r -> r.getRoleId()).collect(Collectors.toList()).contains(item.getId())) {
                            List<GroupUserTreeItem> children = item.getChildren();
                            if (CollectionUtils.isEmpty(children)) {
                                ArrayList<GroupUserTreeItem> userItems = new ArrayList<>();
                                GroupUserTreeItem userItem = new GroupUserTreeItem();
                                userItem.setPerson(true);
                                userItem.setId(userBO.getUserId());
                                userItem.setLabel(userBO.getUserName());
                                userItems.add(userItem);
                                item.setChildren(userItems);
                            } else {
                                GroupUserTreeItem userItem = new GroupUserTreeItem();
                                userItem.setPerson(true);
                                userItem.setId(userBO.getUserId());
                                userItem.setLabel(userBO.getUserName());
                                children.add(userItem);
                            }
                        }
                    }
                }
        );
        List<GroupUserTreeItem> teamUserTreeItems = buildTeamTree();
        return new GroupRoleUserTree(groupUserTreeItems, roleUserTreeItems, teamUserTreeItems);
    }

    /**
     * @author Greekn Zhang
     * @date 2021/5/27 16:21
     * @return java.util.List<com.xy.biz.uc.domain.vo.GroupUserTreeItem>
     * @description 构建团队人员树
     */
    private List<GroupUserTreeItem> buildTeamTree() {
        GroupUserTreeItem teamUserTreeItem = new GroupUserTreeItem();
        List<TeamBO> teamBOS = teamManager.listTeam(TeamQuery.max().build());
        if (CollectionUtils.isEmpty(teamBOS)) {
            return null;
        }
        Map<Long, List<TeamUserRelBO>> map = new HashMap<>();
        if (teamBOS != null) {
            //添加团队
            ArrayList<GroupUserTreeItem> userItems = new ArrayList<>();
            teamBOS.forEach(teamBO -> {
                GroupUserTreeItem userItem = new GroupUserTreeItem();
                userItem.setId(teamBO.getTeamId());
                userItem.setLabel(teamBO.getTeamName());
                userItem.setPerson(false);
                userItems.add(userItem);
                teamUserTreeItem.setChildren(userItems);
                List<TeamUserRelBO> teamUserRelBOS = teamManager.listTeamUserRel(TeamUserRelQuery.builder().teamId(teamBO.getTeamId()).joinStatus(JOIN_STATUS_JOINED).build());
                map.put(teamBO.getTeamId(), teamUserRelBOS);
            });
        }
        //向团队中添加人
        List<GroupUserTreeItem> children = teamUserTreeItem.getChildren();
        children.forEach(team -> {
            if (map.containsKey(team.getId())) {
                List<TeamUserRelBO> teamUserRelBOS = map.get(team.getId());
                ArrayList<GroupUserTreeItem> userItems = new ArrayList<>();
                teamUserRelBOS.forEach(rel -> {
                    GroupUserTreeItem userItem = new GroupUserTreeItem();
                    userItem.setId(rel.getUserId());
                    userItem.setPerson(true);
                    userItems.add(userItem);
                    team.setChildren(userItems);
                });
                if (!CollectionUtils.isEmpty(team.getChildren())) {
                    userClient.buildByUser(team.getChildren(),
                            team.getChildren().stream().map(GroupUserTreeItem::getId).collect(Collectors.toList()),
                            GroupUserTreeItem::getId,
                            (group, userDTO) -> group.setLabel(userDTO.getUserName()));
                }
            }
        });
        return children;
    }

    @Override
    public List<UserBO> searchUser(UserQuery userQuery) {
        List<UserBO> userBOS = userManager.searchUser(userQuery);
        userBOS = userBOS.stream().peek(u -> u.setValue(u.getUserName())).collect(Collectors.toList());
        return userBOS;
    }

    /**
     * 区分条件根据用户名模糊搜索用户
     * @param request
     * @return
     */
    @Override
    public List<UserBO> searchUserByKeyword(SearchUserRequest request) {
        if (request == null) {
            return null;
        }
        List<UserBO> userBOS = new ArrayList<>();
        UserQuery build = UserQuery.max().userName(request.getUserName()).status(request.getStatus()).withUserGroup(true).withRole(true).build();
        List<UserBO> user = userManager.listUser(build);
        //根据公司/中心/部门查询
        if (request.getType() != null && request.getType() == 0 && request.getId() != null && !request.getId().equals(0L)) {
            UserGroupBO userGroup = userGroupService.getUserGroup(UserGroupIdQuery.builder().userGroupIdList(new ArrayList<>(Collections.singleton(request.getId()))).build());
            if (!user.isEmpty() && userGroup != null) {
                userBOS = user.stream().filter(u -> u.getUserGroupBO() != null && u.getUserGroupBO().getUserGroupId().equals(userGroup.getUserGroupId())).collect(Collectors.toList());
            }
        } else if (request.getType() != null && request.getType() == 1 && request.getId() != null && !request.getId().equals(0L)) {
            //根据角色查找
            RoleBO role = roleManager.getRole(RoleIdQuery.builder().roleIdList(new ArrayList<>(Collections.singletonList(request.getId()))).build());
            if (!user.isEmpty()) {
                userBOS = user.stream().filter(u -> u.getRoleBOSet() != null && u.getRoleBOSet().contains(role)).collect(Collectors.toList());
            }
        } else {
            //只根据名字模糊查询
            return user;
        }
        return userBOS;
    }

    /**
     * 根据角色Code模糊搜索用户
     * @param request
     * @return
     */
    @Override
    public List<UserBO> searchUserByCode(SearchUserByCodeRequest request) {
        RoleBO role = roleManager.getRoleByCode(request.getRoleCode());
        if (role == null) {
            return null;
        }
        List<UserBO> userBOS = userManager.listUserByRoleId(new ArrayList<>(Collections.singleton(role.getRoleId())));
        if (userBOS.isEmpty()) {
            return null;
        }
        return userBOS;
    }

    @Override
    public int searchCountUser(UserQuery userQuery) {
        return userManager.countSearchUser(userQuery);
    }

    @Override
    public Result<?> getAllNoGroupUser() {
        return null;
    }

    @Override
    public Result<?> getUsersByGroupId(GetUserGroupRequest request) {
        List<UserBO> usersByGroupId = userManager.getUsersByGroupId(request.getUserGroupId());
        if (CollectionUtils.isEmpty(usersByGroupId)) {
            return Result.success();
        }
        return Result.success(UserConverter.toDTO(usersByGroupId));
    }

    @Override
    public Result<?> removeUserGroupUserRel(RemoveUserGroupUserRelRequest request) {
        int row = userManager.removeUserGroupUserRel(request);
        if (row > 0) {
            return Result.success();
        }
        return Result.ofErrorRowsAffected();
    }

    @Override
    public Collection<Long> listUserIdByUserGroupId(Collection<Long> collection) {
        return userManager.listUserIdByUserGroupId(collection);
    }

    /**
     * @author Greekn Zhang
     * @date 2021/5/7 10:52
     * @description 将人员插入部门树中
     */
    private void getUserItem
    (List<GroupUserTreeItem> groupUserTreeItems, Map<Object, List<GroupUserTreeItem>> userNode) {
        if (groupUserTreeItems == null) {
            return;
        }
        for (GroupUserTreeItem userTreeItem : groupUserTreeItems) {
            if (userTreeItem != null && userTreeItem.getId() != null && userTreeItem.getPerson() != null) {
                if (userNode.containsKey(userTreeItem.getId()) && !userTreeItem.getPerson()) {
                    if (userTreeItem.getChildren() == null) {
                        userTreeItem.setChildren(new ArrayList<>());
                    }
                    userTreeItem.getChildren().addAll(userNode.get(userTreeItem.getId()));
                }
            }
            getUserItem(userTreeItem.getChildren(), userNode);
        }
    }

    /**
     * @author Greekn Zhang
     * @date 2021/5/7 10:51
     * @param treeItems
     * @description 构建公司部门树
     */
    private void getGroupItem(List<TreeItem> treeItems, List<GroupUserTreeItem> g) {
        if (treeItems.isEmpty()) {
            return;
        }
        for (TreeItem tree : treeItems) {
            GroupUserTreeItem gt = new GroupUserTreeItem();
            gt.setId(Long.parseLong(tree.getValue()));
            gt.setLabel(tree.getLabel());
            gt.setPerson(false);
            if (tree.getChildren() != null) {
                gt.setChildren(new ArrayList<>());
                getGroupItem(tree.getChildren(), gt.getChildren());
            }
            g.add(gt);
        }
    }
}
